<?php
/**
 * 	Bushido
 *
 * @category   Bushido
 * @package    Bushido_Controller
 * @subpackage Action
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes
 * @author Nathan Keyes
 * @version    $Id: User.php 17 2009-11-15 01:58:48Z nkeyes $
 */
require_once 'Zend/Controller/Action.php'; 

class Bushido_Controller_Action_User extends Bushido_Controller_Action
{ 
	
	/**
	 * (non-PHPdoc)
	 * @see library/Zend/Controller/Zend_Controller_Action#init()
	 */
	public function init()
	{
		parent::init();
		$this->_requiresAuth = false;

	}
	
	/**
	 * @todo move this to the app child of this class
	 * @return Zend_Dojo_Form
	 */
	public function getLoginForm()
	{
		$loginForm = new Zend_Form();
		$loginForm->setAction($this->getRequest()->getBaseUrl() . '/user/login');
		$loginForm->setMethod('post');
		$loginForm->addElement('text', 'uid', array('label' => 'Login'));
		$loginForm->addElement('password', 'password', array('label' => 'Password'));
		$loginForm->addElement('submit', 'Login', array('value' => ''));
		//$loginForm->addElement('Button', 'login', array('value' => 'Login', 'type' => 'submit', 'dijitParams' => array('value' => 'Login', 'label' => 'Login')));
		return $loginForm;	
	}
	
	
	/**
	 * 
	 * @return void
	 */
	public function indexAction() 
	{
		$this->view->loginForm = $this->getLoginForm();
	}
	
	
	/**
	 * 
	 * @return void
	 */
	public function loginAction() 
	{
		
		$loginForm = $this->_validateForm();
		
        if($loginForm)
        {
			$authResult = $this->_authenticate($loginForm);
			//Zend_Debug::dump($authResult, 'authResult');exit;
        	$this->_actOnAuth($authResult, $loginForm);
        	
        }
	}
	
	protected function _validateForm()
	{
		if(!$this->getRequest()->isPost())
		{
            $this->_forward('index');
            return false;
        }
        else
        {
        	//Zend_Debug::dump($this->getRequest()->isPost());
        }
        $loginForm = $this->getLoginForm();

        if (!$loginForm->isValid($_POST))
		{
            $this->view->loginForm = $loginForm;
			return false;
        }
        return $loginForm;
	}
	
	/**
	 * 
	 * @param Zend_Form $loginForm
	 * @return Zend_Auth_Result
	 */
	protected function _authenticate(Zend_Form $loginForm)
	{
		$formValues = $loginForm->getValues();
		$appConfig = Zend_Controller_Front::getInstance()->getParam('appconfig');
		
		$this->view->showErrorDetails = $appConfig['showerrordetails'];
		
		$authConfig = new Zend_Config_Xml(APPLICATION_PATH . '/configs/auth.xml', APPLICATION_ENV);
		
		$adapter = new Bushido_Auth_Adapter_Ldap($authConfig->ldap->toArray(), $formValues['uid'], $formValues['password']);
		
		$authResult =  Zend_Auth::getInstance()->authenticate($adapter);
		return $authResult;
		
	}
	
	
	/**
	 * 
	 * @param Zend_Auth_Result $authResult
	 * @return void
	 */
	protected function _actOnAuth(Zend_Auth_Result $authResult, Zend_Form $loginForm)
	{
		switch ($authResult->getCode())
		{
		
			case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
				$this->_handleIdentityNotFound($authResult, $loginForm);
				break;
			case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
				$this->_handleInvalidCredential($authResult, $loginForm);
				break;
			
			case Zend_Auth_Result::SUCCESS:
				$this->_handleSuccess($authResult, $loginForm);
				break;
			default:
				$this->_handleDefault($authResult, $loginForm);
				break;
		}	
	}
	
	/**
	 * 
	 * @param $authResult
	 * @return void
	 */
	protected function _handleIdentityNotFound(Zend_Auth_Result $authResult, Zend_Form $loginForm)
	{
		$this->view->loginForm = $loginForm;
		$this->view->messages = $authResult->getMessages();
	}
	
	/**
	 * 
	 * @param $authResult
	 * @return void
	 */
	protected function _handleInvalidCredential(Zend_Auth_Result $authResult, Zend_Form $loginForm)
	{
		$this->view->loginForm = $loginForm;
		$this->view->messages = $authResult->getMessages();
	}
	
	/**
	 * 
	 * @param $uid
	 * @return unknown_type
	 */
	protected function _setUserInfo($uid)
	{
		Bushido_App::setUserInfo($uid);
	}
	
	/**
	 * 
	 * @param $authResult
	 * @return void
	 */
	protected function _handleSuccess(Zend_Auth_Result $authResult, Zend_Form $loginForm)
	{
		$uid = $loginForm->getValue('uid');
		
		//$this->_setUserInfo($uid);
		$this->_setUserInfo($uid);
		$attemptedRequest = Bushido_App::session()->attemptedRequest;
		
		
		if(!$attemptedRequest)
		{
			if($this->_hasParam('useLayout') && $this->_getParam('useLayout') == 'false')
			{
				$this->_helper->redirector('index','index', null, array('useLayout' => 'false'));
				exit;
			}
			else
			{
				$this->_helper->redirector('index','index');
				exit;
			}
		}
		else
		{
			if(isset($attemptedRequest['params']['useLayout']))
			{
				//unset($attemptedRequest['params']['useLayout']);
			}
			$this->_helper->redirector($attemptedRequest['action'], $attemptedRequest['controller'], $attemptedRequest['module'], $attemptedRequest['params']);
			unset(Bushido_App::session()->attemptedRequest);
			exit;
		}
	}
	
	
	/**
	 * 
	 * @param $authResult
	 * @return void
	 */
	protected function _handleDefault(Zend_Auth_Result $authResult, Zend_Form $loginForm)
	{
		$this->view->loginForm = $loginForm;
		$this->view->messages = $authResult->getMessages();
		array_push($this->view->messages, "\$authResult->getCode(): " . $authResult->getCode());
	}
	
	/**
	 * 
	 * @return void
	 */
	public function logoutAction()
	{
		Zend_Session::destroy();
		if($this->_hasParam('useLayout') && $this->_getParam('useLayout') == 'false')
		{
			$this->_helper->redirector('index','user', 'default', array('useLayout' => 'false'));
		}
		else
		{
			$this->_helper->redirector('index','user', 'default');
		}
	}
	
	public function actasuserAction()
	{
		if(!isset(Bushido_App::session()->userInfo['admin_bushido_user_id']))
		{
			throw new Zend_Acl_Exception();
		}
		$this->_helper->layout->disableLayout();
		$form = $this->_getActAsUserForm();
		
		if($this->_hasParam('assumedId') && $form->isValid($this->_getAllParams()))
		{
			$this->_setUserInfo(Bushido_Db_Table::generateRow('Bushido_DbTable_User', $form->getValue('assumedId'))->login);

			$this->_helper->redirector('index', 'index');
		}
		$form->setDefault('assumedId', Bushido_App::getUser()->bushido_user_id);
		$this->view->form = $form;
	}
	
	protected function _getActAsUserForm()
	{
		$form = new Bushido_Form();
		$db = Bushido_App::getAdapter();
		$userMultiOptions = $db->fetchPairs('SELECT bushido_user_id, CONCAT(first_name, " ", last_name) as name FROM Bushido_DbTable_User ORDER BY first_name, last_name');
		$user = $form->createElement
		(
			'FilteringSelect',
			'assumedId',
			array
			(
				'multiOptions' => $userMultiOptions,
				'onchange' => 'window.location = "' . Zend_Controller_Front::getInstance()->getBaseUrl() . '/user/actasuser/assumedId/" + $("#assumedId").val()',
				'id' => 'assumedId',
				'required' => true,
			)
		);
		
		
		$form->addElements(array($user));
		//$form->addResetSubmit('Reset', 'Submit');
		$form->setMethod(Bushido_Form::METHOD_POST);
		return $form;
		
	}
}